﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;

namespace Sharp.UnusedReferences.Options
{
	public partial class UserControlOptionsReset : UserControl
	{
		#region Fields

		bool WasPopulated;

#endregion

		#region Constructors
		
		public UserControlOptionsReset()
		{
			InitializeComponent();
		}

		#endregion

		#region Properties
		
		internal object ObjectToBeRest
		{
			get;
			set;
		}

		#endregion

		#region Public Functions
		
		internal void Populate()
		{
			if(WasPopulated)
			{
				RefreshValues();
			}
			else
			{
				foreach(string strCategoryName in Enum.GetNames(typeof(SettingsCategory)).Reverse())
				{
					PopulateCategory(strCategoryName);
				}
				WasPopulated = true;
			}
		}
		internal void RefreshValues()
		{
			foreach(Control ControlGroupBox in Controls)
			{
				foreach(Control ControlUserControlOptionsEntry in ControlGroupBox.Controls)
				{
					((UserControlOptionsEntry)ControlUserControlOptionsEntry).RefreshValue();
				}
			}
		}

		#endregion

		#region Helper Functions
		
		private static Attribute GetAttribute(PropertyInfo PropertyInfoInstance, Type AttributeType)
		{
			object[] CustomAttributes = PropertyInfoInstance.GetCustomAttributes(AttributeType, false);
			if(CustomAttributes.Length != 0)
			{
				return (Attribute)CustomAttributes[0];
			}
			return null;
		}
		private static string GetCategory(PropertyInfo PropertyInfoInstance)
		{
			Attribute AttributeCategory = GetAttribute(PropertyInfoInstance, typeof(CategoryAttribute));
			if(AttributeCategory != null)
			{
				return ((CategoryAttribute)AttributeCategory).Category;
			}
			return string.Empty;
		}
		private void PopulateCategory(string strCategoryName)
		{
			GroupBox GroupBoxCategory = new GroupBox()
			{
				Text = strCategoryName,
				Dock = DockStyle.Top,
				AutoSize = true,
				AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink
			};
			PopulateProperties(GroupBoxCategory);
			Controls.Add(GroupBoxCategory);
		}
		private void PopulateProperties(GroupBox GroupBoxCategory)
		{
			bool WasHeaderShown = false;
			foreach(PropertyInfo PropertyInfoInstance in ObjectToBeRest.GetType().GetProperties())
			{
				if(GetAttribute(PropertyInfoInstance, typeof(DefaultValueAttribute)) != null && GetCategory(PropertyInfoInstance) == GroupBoxCategory.Text)
				{
					UserControlOptionsEntry UserControlOptionsEntryInstance = new UserControlOptionsEntry(ObjectToBeRest, PropertyInfoInstance, !WasHeaderShown)
					{
						Dock = DockStyle.Bottom
					};
					GroupBoxCategory.Controls.Add(UserControlOptionsEntryInstance);
					WasHeaderShown = true;
				}
			}
		}

		#endregion
	}
}
